package com.grapes.view;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ViewFlipper;
import com.grapes.R;

public class RecruiteInfoListActivity extends GrapesActivity {

	public static final int MSG_CAMPUS_ALREADY = 1;
	public static final int MSG_DAILY_INFO_ALREADY = 2;
	public static final int MSG_NET_APPLICATION_ALREADY = 3;
	
	private RelativeLayout mainBoardGroup;
	private RelativeLayout titleGroup;
	private Boolean isMainBoardHidden = true;
	private ImageView indicator;
	private CampusTalkingListView campusTalkingListView;
	private NetApplicationListView netApplicationListView;
	private DailyInfoListView dailyInfoListView;
	private ViewFlipper viewFlipper;
	private AnimationSet in;
	private AnimationSet out;
	private int screenHeight;
	private GestureDetector gestureDetector;
	private int selectedListViewIndex = 0;

	private Handler handler = new Handler() {
		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			switch (msg.what) {
			case MSG_CAMPUS_ALREADY:
				dismissPorgressDialog();
				((BaseAdapter) (campusTalkingListView.getListViewAdapter()))
						.notifyDataSetChanged();
				break;
			case MSG_DAILY_INFO_ALREADY:
				dismissPorgressDialog();
				((BaseAdapter) (dailyInfoListView.getListViewAdapter()))
						.notifyDataSetChanged();
				break;
			case MSG_NET_APPLICATION_ALREADY:
				dismissPorgressDialog();
				((BaseAdapter) (netApplicationListView.getListViewAdapter()))
						.notifyDataSetChanged();
				break;
			default:
				break;
			}
		}
	};

	private void switchListView(int targetIndex, boolean moveRightward) {
		while (selectedListViewIndex != targetIndex) {
			selectedListViewIndex++;
			selectedListViewIndex=selectedListViewIndex%viewFlipper.getChildCount();
			if (moveRightward) {
				Animation SlideIn = AnimationUtils.loadAnimation(
						RecruiteInfoListActivity.this, R.anim.push_right_in);
				Animation slideOut = AnimationUtils.loadAnimation(
						RecruiteInfoListActivity.this, R.anim.push_right_out);
				viewFlipper.setInAnimation(SlideIn);
				viewFlipper.setOutAnimation(slideOut);
				viewFlipper.showNext();		
			} else {
				Animation SlideIn = AnimationUtils.loadAnimation(
						RecruiteInfoListActivity.this, R.anim.push_left_in);
				Animation slideOut = AnimationUtils.loadAnimation(
						RecruiteInfoListActivity.this, R.anim.push_left_out);
				viewFlipper.setInAnimation(SlideIn);
				viewFlipper.setOutAnimation(slideOut);
				viewFlipper.showPrevious();	
			}
		}
	}

	public Handler getControllerHandler() {
		return handler;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.recruite_info);
		mainBoardGroup = (RelativeLayout) findViewById(R.id.recruite_info_main_board);
		titleGroup = (RelativeLayout) findViewById(R.id.recruite_title_group);
		indicator = (ImageView) findViewById(R.id.title_reveal_indicator);
		screenHeight = getWindowManager().getDefaultDisplay().getHeight();
		// TODO the following two code takes no effect in the OnCreate(Bundle savedInstanceState) method
		// mainBoardGroup.getLayoutParams().height = screenHeight / 2;
		
		mainBoardGroup.layout(0,
				titleGroup.getHeight() - mainBoardGroup.getHeight(),
				mainBoardGroup.getWidth(), titleGroup.getHeight());

		LinearLayout mainPart = (LinearLayout) findViewById(R.id.recruite_info_main_part_group);
		mainPart.layout(0, titleGroup.getHeight(), mainBoardGroup.getWidth(),
				screenHeight);

		campusTalkingListView = (CampusTalkingListView) findViewById(R.id.campus_talking_list);
		netApplicationListView = (NetApplicationListView) findViewById(R.id.net_application_list);
		dailyInfoListView = (DailyInfoListView) findViewById(R.id.daily_info_list);
		viewFlipper = (ViewFlipper) findViewById(R.id.recruite_info_flipper);

		gestureDetector = new GestureDetector(RecruiteInfoListActivity.this,
				new FlingGestureDetector());

		titleGroup.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (isMainBoardHidden) {
					startPushDownInAnimation();
				} else {
					startPushUpOutAnimation();
				}
			}
		});
		showProgressDialog();
		campusTalkingListView.reloadData();
		showProgressDialog();
		netApplicationListView.reloadData();
//		showProgressDialog();
//		dailyInfoListView.reloadData();
	}

	private void startPushDownInAnimation() {
		AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
		TranslateAnimation transalationAnimation;
		if (mainBoardGroup.getTop() == 0) {
			// for some unknown reason, the
			// mainBoardGroup.layout(0,titleGroup.getHeight() -
			// mainBoardGroup.getHeight(),mainBoardGroup.getWidth(),
			// titleGroup.getHeight());
			// in the onCreate function makes no diffirence to the
			// mainBoardGroup.getTop() value
			transalationAnimation = new TranslateAnimation(0, 0, 0,
					titleGroup.getHeight());
		} else

			transalationAnimation = new TranslateAnimation(0, 0, 0,
					mainBoardGroup.getHeight());
		in = new AnimationSet(true);
		in.addAnimation(alphaAnimation);
		in.addAnimation(transalationAnimation);
		in.setInterpolator(new AccelerateDecelerateInterpolator());
		in.setAnimationListener(new VerticalSlideAnimationListener());
		in.setDuration(500);
		mainBoardGroup.clearAnimation();
		mainBoardGroup.startAnimation(in);
	}

	private void startPushUpOutAnimation() {
		if (out == null) {
			AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);
			TranslateAnimation transalationAnimation = new TranslateAnimation(
					0, 0, 0, -mainBoardGroup.getHeight());
			out = new AnimationSet(true);
			out.addAnimation(alphaAnimation);
			out.addAnimation(transalationAnimation);
			out.setInterpolator(new AccelerateDecelerateInterpolator());
			out.setAnimationListener(new VerticalSlideAnimationListener());
			out.setDuration(500);
		}
		mainBoardGroup.clearAnimation();
		mainBoardGroup.startAnimation(out);
	}

	class VerticalSlideAnimationListener implements Animation.AnimationListener {
		@Override
		public void onAnimationStart(Animation animation) {
		}

		@Override
		public void onAnimationRepeat(Animation animation) {

		}

		@Override
		public void onAnimationEnd(Animation animation) {
			if (isMainBoardHidden) {
				// At the end of animation,titleGroup will show up
				mainBoardGroup.layout(0, titleGroup.getHeight(),
						mainBoardGroup.getWidth(), mainBoardGroup.getHeight()
								+ titleGroup.getHeight());
				mainBoardGroup.setVisibility(View.VISIBLE);
			} else {
				// At the end of animation,titleGroup will be hidden
				mainBoardGroup.layout(0, titleGroup.getHeight()
						- mainBoardGroup.getHeight(),
						mainBoardGroup.getWidth(), titleGroup.getHeight());
				mainBoardGroup.setVisibility(View.INVISIBLE);
			}
			isMainBoardHidden = !isMainBoardHidden;
		}
	};

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		gestureDetector.onTouchEvent(ev);
		return super.dispatchTouchEvent(ev);

	}

	class FlingGestureDetector extends GestureDetector.SimpleOnGestureListener {
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			Log.d("GrapesTest", "onFling invoked");
			float lastX = e2.getX();
			float lastY = e2.getY();
			float previousX = e1.getX();
			float previousY = e1.getY();
			int[] flipperLocationInScreen = new int[2];
			viewFlipper.getLocationOnScreen(flipperLocationInScreen);
			float topThreshold = flipperLocationInScreen[1];
			float bottomThreshold = topThreshold + viewFlipper.getHeight();
			if (lastY < topThreshold && previousY < topThreshold)
				return super.onFling(e1, e2, velocityX, velocityY);
			if (lastY > bottomThreshold && previousY > bottomThreshold)
				return super.onFling(e1, e2, velocityX, velocityY);
			if(Math.abs(lastX-previousX)<=MIN_HORIZONTAL_FlING_DISTANCE)
				return super.onFling(e1, e2, velocityX, velocityY);
			if(velocityX<MIN_HORIZONTAL_FLIGN_VALOCITY)
				return super.onFling(e1, e2, velocityX, velocityY);
			Log.d("GrapesTest", "onFling Consumed");
			if (lastX < previousX) {
				int targetIndex=Math.abs(selectedListViewIndex-1)%viewFlipper.getChildCount();
				switchListView(targetIndex, false);
			} else {
				int targetIndex=Math.abs(selectedListViewIndex+1)%viewFlipper.getChildCount();
				switchListView(targetIndex, true);
			}
			return true;
		}
	}
}
